/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:10:15
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-09-21 11:25:53
 * 两栏模式和列表模式的整体查看页面
 */
import React from 'react';
import { routerShape } from 'react-router';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Modal, Button } from 'antd';
import classNames from 'classnames';
import {
  WeaTab,
  WeaSelect,
  WeaErrorPage,
  WeaTools,
  WeaTable,
  WeaFormItem,
  WeaSearchGroup,
  WeaCheckbox,
  WeaTag,
  WeaLocaleProvider,
  WeaAvatar,
  WeaRightMenu,
  WeaPopoverHrm,
} from 'ecCom';
import { WeaSwitch } from 'comsMobx';

import View from './View';
import Layout from './list/Layout';
import LeftList from './list/LeftList';
import TipsOfAutoReceiveEmails from './Inbox/TipsOfAutoReceiveEmails';
import { DropdownMenu, PopoverTodo } from './com';
import {
  listRoute,
  listParams,
  nameUpperCase,
  getFlagCls,
} from '../util/index';
import * as SET_UTILS from '../util/settingUtils';
import WeaCircleImage from '../public/wea-circle-image';
import FormSelect from './list/FormSelect';
import * as EmailUtil from '../util/EmailUtil';

const getLabel = WeaLocaleProvider.getLabel;

const { confirm } = Modal;
const { tryCatch } = WeaTools;
const store = [
  'routing',
  'emailMainStore',
  'emailOpsStore',
  'emailMenuStore',
  'todoNewStore',
].concat(listRoute.map(l => `email${nameUpperCase(l)}Store`));

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@0gmpww`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class List extends React.Component {
  static displayName = 'List';
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
    this.prefixClass = 'wea-email-list';
    this.state = {
      y: 0,
      rowCheckKey: [],
      toHrmId: '',
      toHrmSpan: '',
      fromHrmId: '',
      fromHrmSpan: '',
      refreshSelect: false,
    };
  }
  componentDidMount() {
    const {
      emailMainStore: { setState },
    } = this.props;
    this.isInstanceMounted = true;
    this.doInit();
    $(window).resize(() => {
      this.isInstanceMounted && this.resetTableScrollY();
    });
    setState({ listSearch: this.settingSearch });
  }
  componentWillReceiveProps(nextProps) {
    const { setState } = this.getStoreNow();
    const {
      location: { pathname, key },
      emailMainStore,
    } = this.props;
    const {
      location: {
        pathname: _pathname,
        key: _key,
        query: { ontabchange },
      },
    } = nextProps;
    if (
      (pathname !== _pathname || key !== _key) &&
      !ontabchange &&
      _pathname.indexOf(this.getModName(nextProps)) > 0
    ) {
      const { form } = this.getStoreNow(nextProps);
      this.onClearSelect();
      form.reset();
      this.resetForm();
      emailMainStore.setState({ sortParams: {} });
      this.doInit(nextProps);
      setState({ showSearchAd: false });
      this.setState({ rowCheckKey: [] });
    }
  }
  componentDidUpdate() {
    const {
      emailMainStore: {
        userConfig: { layout },
      },
    } = this.props;
    layout === 3 && this.resetTableScrollY();
  }
  componentWillUnmount() {
    const { setState } = this.getStoreNow();
    this.isInstanceMounted = false;
    $(window).off('resize');
    window.removeEventListener('hashchange', this.autolyReceiveEmails, false);
    setState({ showSearchAd: false });
    this.resetForm();
  }

  autolyReceiveEmails = SET_UTILS.throttle(
    (e, props = this.props) => {
      const {
        location: { pathname },
      } = props;
      const _path = pathname.replace('main/email/', '').split('/')[0];

      if (_path === 'inbox') {
        const {
          emailInboxStore: { autolyGetOuterEmails },
          location: {
            query: { receivemail, receivemailid },
          },
        } = this.props;
        autolyGetOuterEmails(
          receivemail,
          receivemailid,
          // 自动接收成功后，刷新列表
          () => {
            this.doSearch(props, { current: 1 });
            EmailUtil.updateMenuCount();
          },
        );
      }
    },
    true,
    500,
  );

  doInit(props) {
    const curPageStore = this.getStoreNow(props);
    const { quickSeach, form, quickSeachValue } = curPageStore;
    // 头次进入收件箱，则不走该逻辑，当切换至邮件模块其他二级菜单后又切换回收件箱，则走这步，用于
    // 根据高级搜索左侧的weaselect的选中值重置form并更新form某相应值然后搜索
    if (toJS(quickSeach).rows !== undefined) {
      const quickParams = toJS(quickSeach).rows.filter(
        r => r.key === quickSeachValue,
      )[0].params;
      const key = Object.keys(quickParams)[0];
      const value = quickParams[key];
      const formParams = form.getFormParams();
      const formNewValue = {
        subject: { value: formParams.subject },
        [key]: { value },
      };
      form.reset();
      form.updateFields(formNewValue);
    }

    const {
      location: { query, search },
      emailMenuStore,
    } = props || this.props; // getdropDown的参数应该只跟菜单栏有关，而不是高级查询的所有条件
    const params = this.getParams(props);
    const {
      emailMainStore: {
        setState,
        userConfig: { layout },
      },
      emailOpsStore: {
        emailSize: { remainspace },
      },
    } = props || this.props;
    emailMenuStore.setState({
      isNotWeiSearch: !(search.indexOf('subject=') > -1),
    });

    setState({ viewId: '' });
    this.doSearch(props, { current: 1 });
    this.getStoreNow(props).getCondition(params).getdropDown(query);
    layout === 3 && this.resetTableScrollY();
    // const { dropDown } = this.getStoreNow(props);
    // toJS(dropDown).forEach(d => {
    //   this.refs[d.key] && this.refs[d.key].scrollToTop();
    // });

    // 空间不足，不触发自动接收
    if (parseFloat(remainspace) > parseFloat(0)) {
      this.autolyReceiveEmails(null, props || this.props);
      window.addEventListener('hashchange', this.autolyReceiveEmails, false);
    }
  }
  doSearch(props, _params) {
    const params = _params
      ? { ...this.getParams(props), ..._params }
      : this.getParams(props);
    this.getStoreNow(props)
      .getDatas(params, ({ total }) => {
        const {
          emailMainStore: { tabInfo, setState },
        } = props || this.props;
        setState({
          tabInfo: tabInfo.map(t => ({
            ...t,
            title:
              t.tabKey === 'list'
                ? `${t.title.replace(/\s\(\d+\)/g, () => '')} (${total})`
                : t.title,
          })),
        });
        EmailUtil.updateMenuCount();
      })
      .setState({
        selectedRowKeys: [],
      });
    if (this.refs.leftList) {
      this.refs.leftList.wrappedInstance &&
        this.refs.leftList.wrappedInstance.scrollToTop();
    }
  }
  settingSearch = (props, params) => {
    this.doSearch(props, params);
  };
  // reset
  resetTableScrollY() {
    const table = $('.wea-email-list-left-main-collapsed .wea-new-table');
    if (table && table.length > 0) {
      const { top } = table.offset();
      const h = $('.wea-email-main').height();
      const t = $('.wea-email-main').offset().top;
      const y = h - top + t - 80;
      y !== this.state.y && this.setState({ y });
    }
  }
  // on
  onSetTag = (ids, tagId, operation) => {
    const { onSetTag } = this.props;
    typeof onSetTag === 'function' && onSetTag(ids, tagId, operation);
  };
  onCollect = (ids, star) => {
    const { onCollect } = this.props;
    typeof onCollect === 'function' && onCollect(ids, star);
  };

  // 邮件识别发票
  emailOcrInvoice = async (params) => {
    const { emailOcrInvoice } = this.props;
    typeof emailOcrInvoice === 'function' && emailOcrInvoice(params);
  };

  onSetReadStatus = async (ids, status, isLdp, moMessage, type, callback) => {
    if (isLdp) {
      const { emailOpsStore } = this.props;
      await emailOpsStore.setReadStatus(
        { mailIds: `${ids}`, status, type },
        moMessage,
      );
      const { setState, datas } = this.getStoreNow();
      setState(
        {
          selectedRowKeys: [],
          datas: datas.map((d) => {
            const { flagSpan: f, id } = d;
            let flagSpan = { ...f };
            const { className } = flagSpan;
            if (className === 'Ru' && status === 1) {
              flagSpan = { className: 'Rr', labelId: getLabel(25425, '已读') };
            }
            if (className === 'Rr' && status === 0) {
              flagSpan = { className: 'Ru', labelId: getLabel(25396, '未读') };
            }
            return ids.indexOf(id) >= 0 ? { ...d, status, flagSpan } : d;
          }),
        },
        () => {
          if (callback && typeof callback === 'function') {
            callback();
          }
        },
      );
      EmailUtil.updateMenuCount();
    } else {
      const { onSetReadStatus } = this.props;
      typeof onSetReadStatus === 'function' &&
        onSetReadStatus(ids, status, type);
    }
  };
  onDeleteEmail = (ids, operate) => {
    const { onDeleteEmail } = this.props;
    typeof onDeleteEmail === 'function' && onDeleteEmail(ids, operate);
  };
  onMoveToFolder = (ids, folderid, isIn) => {
    const { onMoveToFolder } = this.props;
    typeof onMoveToFolder === 'function' && onMoveToFolder(ids, folderid, isIn);
  };
  onDropDownClick = (key, item) => {
    const { selectedRowKeys } = this.getStoreNow();
    const {
      emailMainStore: { setState },
      location: {
        query: { folderid, labelid },
      },
      todoNewStore,
      leftMenuName,
    } = this.props;
    const { router } = this.context;
    if (key === 'tagManager' || key === 'folderManager') {
      router.push(
        `main/email/setting/${
          key === 'tagManager'
            ? 'labelManage'
            : key === 'folderManager'
            ? 'folderManage'
            : ''
        }`,
      );
    } else if (
      key != 'markAllAsReaded' &&
      selectedRowKeys.length === 0 &&
      key !== 'importEml'
    ) {
      Modal.warning({ content: getLabel(384309, '请先选择需要操作的邮件！') });
    } else if (/^\-?\d+$/.test(key)) {
      if (item.type === 'TAG') {
        // tag
        this.onSetTag(selectedRowKeys, key, 'addLabel');
      } else {
        // folder
        this.onMoveToFolder(selectedRowKeys, key, folderid === key);
      }
    } else if (key === 'cancelAllTag') {
      // tag
      this.onSetTag(selectedRowKeys, '', 'cancelLabel');
    } else if (key === 'markAllAsReaded') {
      this.onSetReadStatus(selectedRowKeys, 1, false, false, 'markAllAsReaded');
    } else if (key === 'markAsReaded' || key === 'markAsUnread') {
      this.onSetReadStatus(
        selectedRowKeys,
        key === 'markAsReaded' ? 1 : 0,
        true,
      );
    } else if (key === 'markAsStart' || key === 'markAsCancelStar') {
      this.onCollect(selectedRowKeys, key === 'markAsStart' ? 1 : 0);
    } else if (key === 'delete' || key === 'remove') {
      confirm({
        content: getLabel(15097, '确定要删除吗？'),
        okText: getLabel(826, '确定'),
        onOk: () =>
          this.onDeleteEmail(
            selectedRowKeys,
            key === 'delete' ? 'delete' : 'deletePermanently',
          ),
      });
    } else if (key === 'markAsWaitdeal') {
      setState({ todoSetVisible: true, todoSetIds: selectedRowKeys });
      todoNewStore.getCondition();
    } else if (key === 'createAndMoveTo') {
      this.onMoveToFolder(selectedRowKeys, key, false);
    } else if (key === 'createAndTagIt') {
      // 新建并标记为
      this.onSetTag(selectedRowKeys, key, 'labelCreate');
    } else if (key === 'exportToDoc') {
      this.onExportToDoc(selectedRowKeys);
    } else if (key === 'exportToCustomerContact') {
      this.onExportToCrm(selectedRowKeys);
    } else if (key === 'exportToEML') {
      this.onExportToEml(selectedRowKeys);
    } else if (key === 'exportToHtml') {
      this.onExportToHtml(selectedRowKeys);
    } else if (key === 'importEml') {
      let operateid = '';
      if (leftMenuName === 'tag') {
        operateid = labelid;
      } else if (leftMenuName === 'folder') {
        operateid = folderid;
      }
      this.onImportEml(selectedRowKeys, leftMenuName, operateid);
    } else {
      confirm({ content: getLabel('506455', '功能开发中') });
    }
  };

  // 列表模式下的打开
  onEmailOpenInTab(id, subject) {
    const { router } = this.context;
    const {
      emailMainStore: { addViewStore },
    } = this.props;
    this.onSetReadStatus([id], 1, true, true, '', () => {
      addViewStore(id, 'inTab');
      subject = subject.replace(/%/g, '/%25');
      router.push(
        `main/email/view?id=${id}&title=${
          subject || getLabel(384186, '查看邮件')
        }`,
      );
    });
  }
  onExportToDoc = (ids) => {
    const { onExportToDoc } = this.props;
    typeof onExportToDoc === 'function' && onExportToDoc(ids);
  };
  onExportToCrm = (ids) => {
    const { onExportToCrm } = this.props;
    typeof onExportToCrm === 'function' && onExportToCrm(ids);
  };

  onPrintEmail = (ids) => {
    const { onPrintEmail } = this.props;
    typeof onPrintEmail === 'function' && onPrintEmail(ids);
  };

  onExportToEml = (ids) => {
    const { onExportToEml } = this.props;
    typeof onExportToEml === 'function' && onExportToEml(ids);
  };

  onExportToHtml = (ids) => {
    const { onExportToHtml } = this.props;
    typeof onExportToHtml === 'function' && onExportToHtml(ids);
  };

  onImportEml = (ids, leftMenuName, operateid) => {
    const { onImportEml } = this.props;
    typeof onImportEml === 'function' &&
      onImportEml(ids, leftMenuName, operateid);
  };

  onTodoClick = (todoSetIds, params = {}) => {
    const { onTodoClick } = this.props;
    typeof onTodoClick === 'function' && onTodoClick(todoSetIds, params);
  };
  onTodoComplete = async (mailIds) => {
    const { onTodoComplete } = this.props;
    typeof onTodoComplete === 'function' && onTodoComplete(mailIds);
  };
  onResetQuickSeachValue() {
    const { setState, quickSeach } = this.getStoreNow();
    const quickSeachValue =
      toJS(quickSeach).rows && toJS(quickSeach).rows[0].key;
    setState({ quickSeachValue });
  }
  onQuickSeach = (quickSeachValue) => {
    const { setState, quickSeach, form } = this.getStoreNow();
    const quickParams = toJS(quickSeach).rows.filter(
      r => r.key === quickSeachValue,
    )[0].params;
    const key = Object.keys(quickParams)[0];
    const value = quickParams[key];
    const formParams = form.getFormParams();
    const formNewValue = {
      subject: { value: formParams.subject },
      [key]: { value },
    };
    form.reset();
    form.updateFields(formNewValue);
    setState({ quickSeachValue });
    this.doSearch('', { current: 1 });
  };
  hide = () => {
    this.refs.leftList.wrappedInstance.hide();
  };
  checkPathInList(props) {
    const {
      location: { pathname },
    } = props || this.props;
    const _path = pathname.replace('main/email/', '').split('/')[0];
    return listRoute.indexOf(_path) >= 0;
  }
  // get
  getModName(props) {
    const {
      location: { pathname },
    } = props || this.props;
    const _path = pathname.replace('main/email/', '').split('/')[0];
    // not use router to change module, need validate
    return listRoute.indexOf(_path) < 0 ? 'inbox' : _path;
  }
  getStoreNow = props =>
    this.props[`email${nameUpperCase(this.getModName(props))}Store`];
  getParams(props) {
    const {
      location: { query },
      emailMainStore,
    } = props || this.props;
    const { toHrmSpan, toHrmId, fromHrmSpan, fromHrmId } = this.state;
    const {
      form,
      pagination: { current },
    } = this.getStoreNow(props);
    const formParams = form.getFormParams();
    delete query.ontabchange;
    let params = {
      ...listParams[this.getModName(props)],
      ...formParams,
      current,
      ...emailMainStore.sortParams,
      ...(this.checkPathInList(props) ? query : {}),
      tohrmid: formParams.to === toHrmSpan ? toHrmId : '',
      fromhrmid: formParams.from === fromHrmSpan ? fromHrmId : '',
    };
    return params;
  }

  onThemeClick = (record) => {
    const { router } = this.context;
    const { id, isInternal, folderid, subject } = record;
    this.setState({ rowCheckKey: [id] });
    this.getModName() === 'draft' || folderid === '-2'
      ? this.onSetReadStatus([id], 1, true, true, '', () => {
          router.push({
            pathname: 'main/email/new',
            query: { isInternal, id, flag: 4 },
          });
        })
      : this.onEmailOpenInTab(id, subject);
  };

  getColumns = () => {
    const { columns } = this.getStoreNow();
    let newColumns = [];
    newColumns = toJS(columns).map((col) => {
      let newCol = { ...col };
      if (
        newCol.dataIndex === 'sendfromSpan' ||
        newCol.dataIndex === 'toSpan'
      ) {
        newCol.width = '20%';
        newCol.sorter = col.dataIndex === 'sendfromSpan';
        newCol.render = (
          text,
          {
            flagSpan: { className, labelId, timingDate },
            sendfromSpan: { imageUrl, realName, title, isInternal, userId },
            toSpan: { realName: r, title: t },
            priority,
            status,
          },
        ) => {
          let listTitle =
            className === 'timingdate' && timingDate
              ? getLabel(509534, '邮件将于{date}发送').replace(
                  '{date}',
                  timingDate,
                )
              : labelId;
          let headerProps = { name: realName, url: imageUrl, userId };
          let headerFlag = col.dataIndex === 'sendfromSpan' && isInternal === 1;
          const _style =
            className === 'Ru' || status === 0 ? { fontWeight: 600 } : {};
          const aProps = userId
            ? {
                href: `javaScript:openhrm(${userId});`,
                onClick: e => window.pointerXY(e),
                style: { ..._style, cursor: 'pointer' },
              }
            : {
                style: _style,
              };
          return (
            <div className={`${this.prefixClass}-table-sendfrom`}>
              <i
                className={getFlagCls(className)}
                title={listTitle}
                style={{ marginRight: priority === '1' ? 0 : 10 }}
              />
              {priority === '1' ? (
                <span
                  title={getLabel(2087, '紧急')}
                  style={{
                    color: '#f00',
                    margin: '0 4px 0 2px',
                    fontSize: 13,
                    verticalAlign: 'middle',
                    fontWeight: 600,
                    cursor: 'default',
                  }}
                >
                  !
                </span>
              ) : null}
              {headerFlag ? (
                <div className="wea-email-avatar">
                  <WeaAvatar
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaAvatar@1fgzr6`}
                    {...headerProps}
                    style={{ width: 40, height: 40 }}
                  />
                </div>
              ) : null}
              {!headerFlag &&
              (col.dataIndex === 'sendfromSpan' ||
                col.dataIndex === 'toSpan') ? (
                <div className="wea-email-avatar">
                  <WeaCircleImage
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaCircleImage@7fia6o`}
                    diameter={40}
                    src={imageUrl || ''}
                    name={realName || r || ''}
                  />
                </div>
              ) : null}
              <WeaPopoverHrm
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaPopoverHrm@v9bhnb`}
              />
              <a
                title={col.dataIndex === 'sendfromSpan' ? title : t}
                {...aProps}
              >
                {col.dataIndex === 'sendfromSpan' ? realName : r}
              </a>
            </div>
          );
        };
        return newCol;
      } else if (newCol.dataIndex === 'subject') {
        newCol.width = '62%';
        newCol.sorter = true;
        newCol.title = <span style={{ paddingLeft: 41 }}>{newCol.title}</span>;
        newCol.render = (
          text,
          {
            subject,
            content,
            hasAttachment,
            labels,
            id,
            flagSpan: { className },
            status,
            emailOcrInvoiceStatus,
          },
        ) => [
          <div className={`${this.prefixClass}-table-tags`}>
            {labels.map(({ color, name, id: tagId }) => (
              <WeaTag
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTag@7c29la@${tagId}`}
                closable
                key={tagId}
                color={color}
                style={{ marginLeft: 10 }}
                title={name}
                onClose={(e) => {
                  e.stopPropagation && e.stopPropagation();
                  e.preventDefault && e.preventDefault();
                  e.nativeEvent && e.nativeEvent.preventDefault();
                  this.onSetTag([id], tagId, 'removeLabel');
                }}
              >
                {name}
              </WeaTag>
            ))}
          </div>,
          <div className={`${this.prefixClass}-table-subject`}>
            {/* 发票识别状态 */}
            <span
              style={{ display: 'inline-block', marginRight: 5, minWidth: 14 }}
            >
              {emailOcrInvoiceStatus && (
                <i
                  title={
                    emailOcrInvoiceStatus === '1'
                      ? '发票已识别'
                      : '发票识别失败，点击可以再次识别。'
                  }
                  style={
                    emailOcrInvoiceStatus === '1'
                      ? {
                          color: '#1BDD3F',
                          'font-size': '18px',
                          position: 'relative',
                          top: 3,
                        }
                      : {
                          color: '#F72B2B',
                          'font-size': '18px',
                          position: 'relative',
                          top: 3,
                        }
                  }
                  className={
                    emailOcrInvoiceStatus === '1'
                      ? getFlagCls('invoice_right')
                      : getFlagCls('invoice_wrong')
                  }
                  onClick={(e) => {
                    if (emailOcrInvoiceStatus === '0') {
                      e.stopPropagation && e.stopPropagation();
                      e.preventDefault && e.preventDefault();
                      e.nativeEvent && e.nativeEvent.preventDefault();
                      this.emailOcrInvoice({ mailid: id });
                    }
                  }}
                />
              )}
            </span>

            <span
              style={{ display: 'inline-block', marginRight: 5, minWidth: 14 }}
            >
              <i className={hasAttachment ? getFlagCls('file') : ''} />
            </span>
            <span
              title={subject}
              style={
                className === 'Ru' || status === 0 ? { fontWeight: 600 } : null
              }
              dangerouslySetInnerHTML={{ __html: subject }}
            />
            <span
              style={{
                'padding-left': '2px',
                color: '#a0a0a0',
                'font-size': '12px',
              }}
            >
              {content ? `-${content}` : ''}{' '}
            </span>
          </div>,
        ];
        return newCol;
      } else if (col.dataIndex === 'sizeSpan') {
        newCol.width = '10%';
        newCol.sorter = true;
        return newCol;
      } else if (col.dataIndex === 'senddateSpan') {
        newCol.width = '18%';
        newCol.sorter = true;
        newCol.render = (
          text,
          { senddateSpan, starred, id, waitdeal, waitdealBean },
        ) => (
          <div className={`${this.prefixClass}-table-senddate`}>
            <span dangerouslySetInnerHTML={{ __html: senddateSpan }} />
            <span
              className={`${this.prefixClass}-table-senddate-ops`}
              onClick={this.stopProOps}
            >
              {waitdeal ? (
                <PopoverTodo
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_PopoverTodo@511ei0`}
                  data={waitdealBean}
                  onTodoClick={p =>
                    this.onTodoClick([id], { ...waitdealBean, ...p })
                  }
                  onTodoComplete={() => this.onTodoComplete([id])}
                >
                  <span title={getLabel(384239, '查看待办信息')}>
                    <i className={getFlagCls('agency', 'n')} />
                  </span>
                </PopoverTodo>
              ) : (
                <i
                  className={getFlagCls('agency', 'o')}
                  title={getLabel(384240, '设置待办')}
                  onClick={() => this.onTodoClick([id])}
                />
              )}
              <i
                className={getFlagCls('fav', starred ? 'n' : 'o')}
                title={
                  starred
                    ? getLabel(81297, '取消星标')
                    : getLabel(384242, '标记星标')
                }
                onClick={() => this.onCollect([id], starred ? 0 : 1)}
              />
            </span>
          </div>
        );
        return newCol;
      }

      newCol.width = '18%';
      return newCol;
    });
    return newColumns;
  };
  stopProOps = (e) => {
    e.stopPropagation && e.stopPropagation();
    e.preventDefault && e.preventDefault();
    e.nativeEvent && e.nativeEvent.preventDefault();
  };
  getRowSelection() {
    const { selectedRowKeys, setState } = this.getStoreNow();
    return {
      selectedRowKeys: toJS(selectedRowKeys),
      onChange: (keys, datas) =>
        setState({ selectedRowKeys: datas.map(d => d.id) }),
    };
  }
  getPagination = p => ({
    ...p,
    onChange: (v) => {
      const {
        emailMainStore: {
          userConfig: { layout },
        },
      } = this.props;
      const hideRight = layout === 3;
      this.getStoreNow().setState({
        pagination: { ...p, current: v },
        selectedRowKeys: [],
      });
      if (!hideRight) {
        this.doSearch('', { current: v });
      }
    },
    showTotal: () =>
      `${getLabel(18609, '共')} ${p.total} ${getLabel(18256, '条')}`,
    showQuickJumper: true,
  });
  onClearSelect = () =>
    this.setState({
      toHrmId: '',
      toHrmSpan: '',
      fromHrmId: '',
      fromHrmSpan: '',
    });

  onEnterSearch = () => {
    const { setState } = this.getStoreNow();
    this.doSearch('', { current: 1 });
    setState({ showSearchAd: false, selectedRowKeys: [] });
    this.onResetQuickSeachValue();
  };

  handleChange = (key, val) => {
    const { form } = this.getStoreNow();
    form.updateFields({ [key]: { value: val || '' } });
  };
  handleSelect = (value, id, key) => {
    this.setState({
      [`${key}HrmId`]: id,
      [`${key}HrmSpan`]: value || '',
    });
  };
  getSearchs(hideRight) {
    const { condition, form } = this.getStoreNow();
    const { isFormInit } = form;
    const group = [];
    isFormInit &&
      condition.forEach((c) => {
        let items = [];
        c.items.forEach((field) => {
          if (field.isQuickSearch) {
            this.quickSearchPara = field.domkey[0];
          }
          if (field.domkey[0] === 'to' || field.domkey[0] === 'from') {
            items.push({
              com: (
                <FormSelect
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_FormSelect@ixro1b@${field.domkey[0]}`}
                  form={form}
                  field={field}
                  handleChange={this.handleChange}
                  handleSelect={this.handleSelect}
                  refreshSelect={this.state.refreshSelect}
                />
              ),
              colSpan: 1,
            });
          } else {
            items.push({
              com: (
                <WeaFormItem
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaFormItem@kd141j@${field.domkey[0]}`}
                  label={`${field.label}`}
                  labelCol={{ span: field.labelcol }}
                  wrapperCol={{ span: field.fieldcol }}
                >
                  <WeaSwitch
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaSwitch@o74gcu@${field.domkey[0]}`}
                    fieldConfig={field}
                    form={form}
                    onEnterSearch={this.onEnterSearch}
                  />
                </WeaFormItem>
              ),
              colSpan: 1,
            });
          }
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@f0yvwv@${c.title}`}
            needTigger={true}
            title={c.title}
            showGroup={c.defaultshow}
            items={items}
            col={hideRight ? 2 : 1}
          />,
        );
      });
    return group;
  }
  resetForm = () => {
    const { form, name } = this.getStoreNow();
    form.reset();
    if (name === 'doing') {
      form.updateFields({ waitdeal: '1' });
    } else if (name === 'inner') {
      form.updateFields({ isInternal: '1' });
    } else if (name === 'star') {
      form.updateFields({ star: '1' });
    }
    this.onResetQuickSeachValue();
    this.setState({ refreshSelect: true }, () => {
      this.setState({ refreshSelect: false });
    });
  };
  onTabSearch = () => {
    const { setState } = this.getStoreNow();
    this.doSearch('', { current: 1 });
    setState({ showSearchAd: false, selectedRowKeys: [] });
    this.onResetQuickSeachValue();
  };
  onTabCancel = () => this.getStoreNow().setState({ showSearchAd: false });
  getButtonAd = () => [
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@dw9zsg@doSearch`}
      type="primary"
      onClick={this.onTabSearch}
    >
      {getLabel(197, '搜索')}
    </Button>,
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@qs0d92@reset`}
      type="ghost"
      onClick={this.resetForm}
    >
      {getLabel(2022, '重置')}
    </Button>,
    <Button
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_Button@52lvv4@cancel`}
      type="ghost"
      onClick={this.onTabCancel}
    >
      {getLabel(201, '取消')}
    </Button>,
  ];
  getDropDown = () => {
    const { datas, dropDown, setState, selectedRowKeys } = this.getStoreNow();
    let downMenus = (
      <div className={`${this.prefixClass}-left-tab-ops-dropdown`}>
        {toJS(dropDown).map((d, index) => (
          <DropdownMenu
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_DropdownMenu@2onv1x@${index}`}
            data={d}
            onClick={this.onDropDownClick}
          />
        ))}
      </div>
    );
    return [
      <WeaCheckbox
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaCheckbox@mrygw3@check`}
        value={
          selectedRowKeys.length === datas.length && datas.length > 0
            ? '1'
            : '0'
        }
        onChange={v =>
          setState({
            selectedRowKeys: v === '1' ? toJS(datas).map(d => d.id) : [],
          })
        }
      />,
    ].concat(downMenus);
  };

  hideSearchAd = () => this.getStoreNow().setState({ showSearchAd: false });
  onSearch = () => {
    this.doSearch('', { current: 1 });
    this.getStoreNow().setState({ selectedKeys: [] });
  };
  onSearchChange = value =>
    this.getStoreNow().form.updateFields({ subject: { value } });

  setShowSearchAd = bool =>
    this.getStoreNow().setState({ showSearchAd: bool });
  getLeft() {
    const {
      showSearchAd,
      datas,
      pagination: _pagination,
      tableLoading,
      quickSeach,
      quickSeachValue,
      columns,
      form,
    } = this.getStoreNow();
    const {
      emailMainStore: {
        userConfig: { layout },
      },
    } = this.props;
    const hideRight = layout === 3;
    const { y } = this.state;
    const tabCls = classNames({
      [`${this.prefixClass}-left-tab`]: true,
      [`${this.prefixClass}-left-tab-collapsed`]: hideRight,
    });
    const listCls = classNames({
      [`${this.prefixClass}-left-main`]: true,
      [`${this.prefixClass}-left-main-collapsed`]: hideRight,
    });
    const options = quickSeach.rows
      ? toJS(quickSeach.rows).map(row => ({
          ...row,
          showname: (
            <div
              className={classNames({
                [`${this.prefixClass}-left-tab-select-ops`]: true,
                [`${this.prefixClass}-left-tab-select-ops-line`]: row.hasLine,
              })}
            >
              <span
                className={`${this.prefixClass}-left-tab-select-ops-icon`}
                style={{ position: 'absolute' }}
              >
                <i className={row.icon || ''} />
              </span>
              <span className="activeOps" style={{ marginLeft: 16 }}>
                {row.showname}
              </span>
            </div>
          ),
        }))
      : [];
    const pagination = this.getPagination(toJS(_pagination));
    const formParams = form.getFormParams();
    // if (quickSeachValue !== '') {
    //   this.onQuickSeach(quickSeachValue);
    // }
    const themeFontSize =
      localStorage.getItem('theme-themeInfo') &&
      JSON.parse(localStorage.getItem('theme-themeInfo')).themeFontSize;
    const userLanguage = window.e9_locale && window.e9_locale.userLanguage;
    const themeClass = classNames({
      [`${this.prefixClass}-left-tab-ops`]: true,
      hideRight,
      bigFont: themeFontSize === '16',
      english: userLanguage === 8,
    });
    return (
      <div className={`${this.prefixClass}-left-wrap`}>
        <TipsOfAutoReceiveEmails
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_TipsOfAutoReceiveEmails@ld998h`}
          location={this.props.location}
        />
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@tkpwxz`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <div className={tabCls}>
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@za146u`}
              rightStyle={{
                width: '100%',
                padding: '0 100px 0 110px',
                backgroundColor: '#fafafa',
              }}
              buttons={[
                <WeaSelect
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaSelect@ewp8v4@select`}
                  value={quickSeachValue}
                  dropdownClassName={`${this.prefixClass}-left-tab-select`}
                  className={`${this.prefixClass}-left-tab-select-Bar`}
                  options={options}
                  onChange={this.onQuickSeach}
                />,
              ]}
              buttonsAd={this.getButtonAd()}
              searchType={['base', 'advanced']}
              searchsBaseValue={formParams.subject || ''}
              searchsAd={this.getSearchs(hideRight)}
              showSearchAd={showSearchAd}
              setShowSearchAd={this.setShowSearchAd}
              hideSearchAd={this.hideSearchAd}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />
            <div className={themeClass}>{this.getDropDown()}</div>
          </div>
          <div className={listCls}>
            {hideRight ? (
              <WeaTable
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTable@4na1em`}
                rowKey="id"
                scroll={{ y }}
                key={`list-${this.props.location.key}`} // 添加Key-解决切换页面表格排序还存在的问题
                loading={tableLoading}
                columns={this.getColumns()}
                dataSource={toJS(datas)}
                rowSelection={this.getRowSelection()}
                pagination={pagination}
                onChange={this.handleTableChange}
                hasOrder
                rowCheckKey={this.state.rowCheckKey}
                needRowClick
                onRowClick={this.onThemeClick}
              />
            ) : (
              <LeftList
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_LeftList@6kbucs`}
                ref="leftList"
                modName={this.getModName()}
                rowKey="id"
                loading={tableLoading}
                dataSource={toJS(datas)}
                columns={toJS(columns)}
                rowSelection={this.getRowSelection()}
                pagination={pagination}
                onTodoClick={this.onTodoClick}
                onTodoComplete={this.onTodoComplete}
                onSetTag={this.onSetTag}
                onCollect={this.onCollect}
                onSetReadStatus={this.onSetReadStatus}
                emailOcrInvoice={this.emailOcrInvoice}
              />
            )}
          </div>
        </WeaRightMenu>
      </div>
    );
  }

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { setState } = this.getStoreNow();
    if (key == 'search') {
      this.doSearch('', { current: 1 });
      setState({ selectedKeys: [] });
    }
  };

  handleTableChange = (pagination, filters, sorter) => {
    const {
      emailMainStore: { setState },
    } = this.props;
    let sortType = sorter.order === 'descend' ? 'DESC' : 'ASC';
    let sortColumn = sorter.column ? sorter.column.orderkey : '';
    let params = { current: pagination.current };
    if (sortColumn) {
      params = { ...params, sortColumn, sortType };
      setState({ sortParams: { sortColumn, sortType } });
    } else {
      setState({ sortParams: {} });
    }
    this.doSearch('', params);
  };
  refreshList = () => {
    const {
      pagination: { current },
    } = this.getStoreNow();
    this.doSearch('', { current });
  };

  render() {
    const { location, emailMainStore } = this.props;
    const {
      viewId,
      userConfig,
      userConfig: { layout: l },
      setState,
    } = emailMainStore;
    const { saveLayout } = this.getStoreNow();
    const hideRight = l === 3;
    const viewProps = {
      location,
      id: viewId,
      viewType: 'inList',
      onSetTag: this.onSetTag,
      onCollect: this.onCollect,
      onSetReadStatus: this.onSetReadStatus,
      onDeleteEmail: this.onDeleteEmail,
      onMoveToFolder: this.onMoveToFolder,
      onTodoClick: this.onTodoClick,
      onTodoComplete: this.onTodoComplete,
      onExportToDoc: this.onExportToDoc,
      onExportToCrm: this.onExportToCrm,
      onExportToEml: this.onExportToEml,
      onExportToHtml: this.onExportToHtml,
      onPrintEmail: this.onPrintEmail,
      emailOcrInvoice: this.emailOcrInvoice,
    };
    if (l === undefined) return null;
    return (
      <div className={this.prefixClass}>
        <Layout
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Layout@1yysxm`}
          showRight={!hideRight}
          leftCom={this.getLeft()}
          onCollapse={(v) => {
            const layout = v ? 3 : 2;
            setState({ userConfig: { ...toJS(userConfig), layout } });
            saveLayout({ layout });
            this.setState({ rowCheckKey: [] });
          }}
        >
          <View
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_View@1w0kes`}
            {...viewProps}
            onIframeClick={this.hide}
            refreshList={this.refreshList}
          />
        </Layout>
      </div>
    );
  }
}

export default List;
